import pandas as pd
from typing import Dict

from interfaces.transformers import IJoiner
from constants import SUBJECT_NUMBER


class JoinerTransformer(IJoiner):
    def join_tables_by_subject(self, base_df: pd.DataFrame, input_excel_path: str, join_key: str = SUBJECT_NUMBER, skip_missing_key: bool = False) -> Dict[str, pd.DataFrame]:
        base_df[join_key] = base_df[join_key].astype(str)
        excel_file = pd.ExcelFile(input_excel_path)
        sheets = excel_file.sheet_names
        result_dict: Dict[str, pd.DataFrame] = {}
        for sheet in sheets:
            current_df = pd.read_excel(input_excel_path, sheet_name=sheet, dtype=str, keep_default_na=False, na_values=[])
            if join_key not in current_df.columns:
                if skip_missing_key:
                    continue
                else:
                    raise ValueError(f"表 '{sheet}' 中缺少连接关键字 '{join_key}'")
            current_df[join_key] = current_df[join_key].astype(str)
            duplicate_columns = [col for col in current_df.columns if col != join_key and col in base_df.columns]
            if duplicate_columns:
                current_df = current_df.drop(columns=duplicate_columns)
            merged_df = current_df.merge(base_df, on=join_key, how='left')
            base_columns = [col for col in base_df.columns if col != join_key]
            other_columns = [col for col in merged_df.columns if col not in base_columns and col != join_key]
            # 统一将 DSFAST 置于第一列，其后为连接键，再是其它基表列和当前表列
            dsfast_first = ['DSFAST'] if 'DSFAST' in merged_df.columns else []
            new_column_order = dsfast_first + [join_key] + [c for c in base_columns if c not in dsfast_first] + other_columns
            merged_df = merged_df[new_column_order]
            result_dict[sheet] = merged_df
        return result_dict